package database;

import java.sql.*;

public class DataBaseConnection {
    private static String connectionUrl;

    public static Connection getConnection() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver").getConstructor().newInstance();
            return DriverManager.getConnection(connectionUrl);
        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
            return null;
        } catch (ClassNotFoundException e) {
            System.out.print("驱动程序未找到:" + e.getMessage());
            e.printStackTrace();
            return null;
        } catch (ReflectiveOperationException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static ResultSet query(Connection connection, String sql) {
        try {
            Statement statement = connection.createStatement();
            return statement.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void closeConnection(Connection connection) {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void setConnnectionURL(String connectionUrl) {
        DataBaseConnection.connectionUrl = connectionUrl;
    }
}
